package com.project.sianet.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpVersion;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.project.sianet.MainActivity;
import com.project.sianet.R;
import com.project.sianet.data.NoticiaArrayAdapter;
import com.project.sianet.data.Client.NoticiaClient;
import com.project.sianet.data.HttpClient.NoticiaHttpClient;
import com.project.sianet.entidades.Noticia;
import com.project.sianet.util.AlertDialogManager;
import com.project.sianet.util.ConnectionDetector;
import com.project.sianet.util.SessionManager;
import com.project.sianet.util.extenders.SianetApplication;

public class NoticiasFragment extends Fragment implements OnScrollListener {
	
	// Session Manager Class
//    SessionManager session;
	
	private int mTitleFrag;
	private NoticiaClient client;
	private List<Noticia> mNoticias= new ArrayList<Noticia>();
	private NoticiaArrayAdapter mAdapter;
	private ProgressDialog progressDialog = null;
	private String lastRequestURI;
	private ListView lv;
	
	private final int AUTOLOAD_THRESHOLD = 4;
//	private final int MAXIMUM_ITEMS = 52;
	private View mFooterView;
	private Handler mHandler;
	private boolean mIsLoading = false;
    private boolean mMoreDataAvailable = true;
    private boolean mWasLoading = false;
    
    // Clase Connection detector
    ConnectionDetector cd;
	
    public NoticiasFragment() {}
    
    public static final NoticiasFragment newInstance() {
    	NoticiasFragment f = new NoticiasFragment();
    	Bundle args = new Bundle();
    	args.putInt("mTitleFrag", R.string.title_bar_noticias);
    	f.setArguments(args);
    	return f;
    }
    
	private Runnable mAddItemsRunnable = new Runnable() {
        @Override
        public void run() {
            mAdapter.addMoreItems(10);
            mIsLoading = false;
        }
    };
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_noticias, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Creo la instancia de Connection detector
        cd = new ConnectionDetector(getActividad().getApplicationContext());
		
        mTitleFrag = getArguments().getInt("mTitleFrag");
        
        mHandler = new Handler();

		TextView title = (TextView)this.getActivity().findViewById(R.id.tv_title);
		title.setText(mTitleFrag);
		
		cargarNoticias();
		
		//setSlidingActionBarEnabled(false);
        
	}
	
	private void onSelectedNoticiaItemClick(AdapterView<?> parent, View view, int position, long id) { 
    	NoticiaArrayAdapter arrayNoticia = (NoticiaArrayAdapter) parent.getAdapter();
    	Noticia not = arrayNoticia.getItem(position);
    	
    	// Ejecuto el proceso que marca como leida la noticia
    	// siempre y cuando no haya sido leida
    	if (not.getNotNoLeida())
    		new TareaWSMarcarLeida(not.getNotCodigo()).execute();
    	
    	Fragment newContent = NoticiaDetalleFragment.newInstance(not);
    	switchFragment(newContent);
    	
    }
	
	private void switchFragment(Fragment fragment) {
 		if (getActivity() == null)
 			return;
 		
 		if (getActivity() instanceof MainActivity) {
 			MainActivity ma = (MainActivity) getActivity();
 			ma.switchContent(fragment);
 		}
 	}
	
	private void cargarNoticias() {
			
		new TareaWSObtenerNoticias().execute();
		
	}
	
	class TareaWSMarcarLeida extends AsyncTask<Integer,Void,Void> {
        
        int id;
        public TareaWSMarcarLeida(int id) {
        	this.id = id;
        }

        @Override
		protected Void doInBackground(Integer... params) {

        	if (!cd.hayConexionAInternet()) {
        		switchFragment(new NetworkLostFragment());
        		return null;
        	}
        	
        	getNoticiaClient().marcarLeida(SessionManager.usuarioLogeado(), Integer.toString(id), SessionManager.codigoIMEI());
			return null;
			
		}
        
    }
	
	private class TareaWSObtenerNoticias extends AsyncTask<String,Integer,List<Noticia>> {
		
		@Override
        protected void onPreExecute(){ 
           super.onPreExecute();
           
           progressDialog = new ProgressDialog(getActividad());
           progressDialog.setCancelable(false);
           progressDialog.show();        
           progressDialog.setContentView(R.layout.custom_progressdialog);

        }
		
		@Override
		protected List<Noticia> doInBackground(String... params) {

			if (cd.hayConexionAInternet()) {
				try {
					NoticiaClient client = getNoticiaClient();
					if (client != null)
						return client.Noticia_getAllByUsuario(String.valueOf(SessionManager.perfilLogeado()), SessionManager.usuarioLogeado());
					else
						return null;
				} catch (Exception ex) {
					return new ArrayList<Noticia>();
				}
			} else
				return null;
			
		}
		
		protected void onPostExecute(List<Noticia> noticias) {
			
			progressDialog.dismiss();
			
			if (noticias == null) {
				switchFragment(new NetworkLostFragment());
				return;
			}
			
			if (noticias.size() > 0) {
	            	
				mNoticias = noticias;

//		        NoticiaArrayAdapter adapter = new  NoticiaArrayAdapter(getActividad(), R.layout.noticias_list, mNoticias);
		        mAdapter = new  NoticiaArrayAdapter(getActividad(), R.layout.noticias_list, mNoticias);
		        mFooterView = LayoutInflater.from(getActividad().getApplicationContext()).inflate(R.layout.custom_loaderpage, null);
		        
				lv = (ListView) getActividad().findViewById(R.id.lv_noticias);
//				lv.addFooterView(mFooterView, null, false);
				lv.setAdapter(mAdapter);
				
//				lv.setOnScrollListener(new OnScrollListener() {
//					
//					@Override
//					public void onScrollStateChanged(AbsListView view, int scrollState) {
//						// TODO Auto-generated method stub
//						
//					}
//					
//					@Override
//					public void onScroll(AbsListView view, int firstVisibleItem,
//							int visibleItemCount, int totalItemCount) {
//						
//						if (!mIsLoading && mMoreDataAvailable) {
//				            if (totalItemCount >= mAdapter.getCurrentCount()) {
//				                mMoreDataAvailable = false;
//				                lv.removeFooterView(mFooterView);
//				            }else
//				            	if (totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem + visibleItemCount) {
//				                mIsLoading = true;
//				                mHandler.postDelayed(mAddItemsRunnable, 1000);
//				            }
//				        }
//						
//					}
//				});
				
				lv.setOnItemClickListener(new OnItemClickListener() {
					
		            @Override
		            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		                onSelectedNoticiaItemClick(parent, view, position, id);
		            }
	            
				});
	            	
			} else {
	            	
				AlertDialogManager.showToastMessage(getActividad(), getString(R.string.no_hay_noticias_publicadas));
	            	
			}
			
		}
		
	}
	
	@Override
    public void onStart() {
        super.onStart();
        if (mWasLoading) {
            mWasLoading = false;
            mIsLoading = true;
            mHandler.postDelayed(mAddItemsRunnable, 1000);
        }
    }
	
	@Override
    public void onStop() {
        super.onStop();
        mHandler.removeCallbacks(mAddItemsRunnable);
        mWasLoading = mIsLoading;
        mIsLoading = false;
    }
	
	private NoticiaClient getNoticiaClient() {

        String requestURI = SianetApplication.getRequestURI(getActividad());
		if (requestURI != null) {
	        if (client == null || !requestURI.equals(lastRequestURI)) {
	            BasicHttpParams params = new BasicHttpParams();
	            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	            HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
	            HttpProtocolParams.setUseExpectContinue(params, false);
//	            client = ProxyFactory.create(NoticiaClient.class, requestURI, new ApacheHttpClient4Executor(params));
	            client = new NoticiaHttpClient(getActividad());
	            lastRequestURI = requestURI;
	        }
	        return client;
		} else
			return null;
		
	}
	
	private Activity getActividad(){
		return this.getActivity();
	}

	@Override
	public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		
	}
	
}
